

#include <Core/logger/logger.h>
#include "servertask.h"
//#include "script/scriptenvironmentex.h"
#include <QtNetwork/QSslCipher>
#include <QtNetwork/QSslSocket>
#include <helpers/sslserver.h>

class ServerTaskPrivate
{
    public:
        ServerTaskPrivate():
            client(0)
        {}

        ~ServerTaskPrivate() {}
        Opl::Helpers::SslServer* client;
        int socketDescriptor;
        //Opl::Scripting::ScriptEnvironment* environment;
};

ServerTask::ServerTask(int socketDescriptor) :
    Opl::Core::Task(0),  O_PRIVATE_CREATE(ServerTask)
{
    O_D(ServerTask);
    d->client = new Opl::Helpers::SslServer(socketDescriptor);
    d->socketDescriptor = socketDescriptor;
}

ServerTask::~ServerTask()
{
    O_PRIVATE_DELETE;
}

void ServerTask::result(const QString& res)
{
    O_D(ServerTask);

    if (d->client)
    {
        LI.Trace() << "Write result:" << res;
        d->client->Send(res);// write(res.toUtf8());
    }
}

void ServerTask::setup()
{
    O_D(ServerTask);
    connect(d->client, SIGNAL(output(const QString&)), this, SLOT(readyCommand(const QString&))/*, Qt::DirectConnection*/);
    connect(d->client, SIGNAL(disconnected()), this, SLOT(socketDisconnected()));
    //d->environment = new ScriptEnvironmentEx(ScriptEnvironmentEx::full, this);
    //connect(d->environment, SIGNAL(output(QString)), this, SLOT(result(QString)));
    //d->environment->initialize();

    d->client->start();
}

void ServerTask::cleanup()
{
    O_D(ServerTask);
    d->client->stop();
    d->client->deleteLater();
    //d->environment->deleteLater();
}

void ServerTask::run()
{
    QTimer::singleShot(0, this, SLOT(setup()));
    exec();
    cleanup();
    //QTimer::singleShot(0, this, SLOT(cleanup()));
}

void ServerTask::readyCommand(const QString& out)
{
    O_D(ServerTask);
    QString line = out.trimmed();
    //LI.Debug() << QString("Client command:%1").arg(QString(arr));

    //if (!d->environment->exec(line, false))
    //{
     //   result(QString("command failed:%1").arg(out));
    //} else {
    //    result(" ");
    //}
        result(line);
}

void ServerTask::socketDisconnected()
{
    Opl::Helpers::SslServer* client = (Opl::Helpers::SslServer*)sender();
    LI.Debug() << QString("Client disconnected:%1").arg(client->socket()->peerAddress().toString());
    quit();
}
